//
//  QRCodeManager.m
//  二维码识别
//
//  Created by 王虎彬 on 16/6/13.
//  Copyright © 2016年 王虎彬. All rights reserved.
//

#import "QRCodeManager.h"
#import <AVFoundation/AVFoundation.h>


@interface QRCodeManager ()  <AVCaptureMetadataOutputObjectsDelegate>


@property (nonatomic ,copy) void(^resultCallBack)(NSArray *results);


@end


@implementation QRCodeManager

//设计一个单例(面试重要)
static QRCodeManager *_instance;

+ (instancetype)shareInstance{

    static dispatch_once_t onceToken;
    
    dispatch_once (&onceToken, ^{
    
        _instance = [[self alloc]init];
    
    });
    
    return _instance;
    
}


#pragma mark - 生成二维码代码

- (UIImage *)generateHDImageWithMsg:(NSString *)inputMsg fgImage:(UIImage *)fgImage{

    //2.1创建滤镜(name = "CIQRCodeGenerator")
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    
    // 2.1.2.设置生成的二维码的容错率
    // key = inputCorrectionLevel value = @"L/M/Q/H"
    [filter setValue:@"H" forKeyPath:@"inputCorrectionLevel"];
    
    //2.2设置输入(KVC)
    // 注意:key = inputMessage, value必须是NSData类型
    NSData *inputData = [inputMsg dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:inputData forKeyPath:@"inputMessage"];
    
    //2.3设置输出
    CIImage *img = [filter outputImage];
    //拿到高清图
    UIImage *hdImage = [self creatHDImageWithCIImage:img];
    
    //制成完整的二维码图
    //拿到前景图
    UIImage *foreImage = [UIImage imageNamed:@"erha"];
    //生成二维码
    UIImage *result = [self creatHDImageWithHDImage:hdImage withFgImage:foreImage];
    
    return result;
}

- (UIImage *)creatHDImageWithCIImage:(CIImage *)CIImage{
    
    //创建拉伸规则
    CGAffineTransform transform = CGAffineTransformMakeScale(10, 10);
    
    //根据规则拉伸放大
    CIImage = [CIImage imageByApplyingTransform:transform];
    
    return [UIImage imageWithCIImage:CIImage];
    
}

- (UIImage *)creatHDImageWithHDImage:(UIImage *)HDImage withFgImage: (UIImage *)fgImage{
    
    //高清图的size
    CGSize size = HDImage.size;
    
    //开启图形上下文
    UIGraphicsBeginImageContext(size);
    
    //高清图画到上下文
    [HDImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    //前景图画到上下文
    CGFloat w = 80;
    CGFloat h = 80;
    CGFloat x = (size.width - w) * 0.5;
    CGFloat y = (size.height - h) * 0.5;
    [fgImage drawInRect:CGRectMake(x, y, w, h)];
    
    //获取当前的图形
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
    return img;
    
}





#pragma mark - 识别二维码代码
- (NSArray *)detectorQRCodeWithQRCodeImage:(UIImage *)qrCodeImage{

    // 1.创建过滤器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:nil];
    
    // 2.获取CIIImage对象
    CIImage *ciImage = [[CIImage alloc] initWithImage:qrCodeImage];
    
    // 3.识别图片中的二维码
    NSArray *features = [detector featuresInImage:ciImage];
    
    // 4.遍历数组,拿到二维码信息
    for (CIQRCodeFeature *f in features) {
        NSLog(@"%@", f.messageString);
    }

    return features;
    
}


#pragma mark - 扫描二维码

#pragma mark 开始扫描
- (void)startScanningQRCodeWithInView:(UIView *)inView  scanView:(UIView *)scanView resultCallback:(void(^)(NSArray *results))callback{

    //1.创建输入
    
    //1.1定义错误
    NSError *error = nil;
    //1.2获取摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //1.3创建输入(这里的error是说把错误信息输出到哪里)
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    if (error != nil) {
        return;
    }
    
    
    
    //2.创建输出
    //2.1创建输出
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    //2.2设置输出的代理和队列
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //3.创建捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc]init];
    
    [session addInput:input];
    
    [session addOutput:output];
    
    //4.设置输入的内容类型
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    
    
    
    
    //5.添加预览图层(让用户看到扫描的界面)
    
    //5.1创建图层
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
    
    //5.2设置frame
    previewLayer.frame = inView.bounds;
    
    //5.3添加到某个图层中
    [inView.layer insertSublayer:previewLayer below:scanView.layer];
    
    
    
    
    //6.设置扫描区域
    // 6.设置扫描区域
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat x = scanView.frame.origin.y / screenSize.height;
    CGFloat y = scanView.frame.origin.x / screenSize.width;
    CGFloat w = scanView.frame.size.height / screenSize.height;
    CGFloat h = scanView.frame.size.width / screenSize.width;
    output.rectOfInterest = CGRectMake(x, y, w, h);
    
    
    
    
    
    
    //7.开始扫描
    [session startRunning];
    
}




#pragma mark - 实现AVCaptureMetadataOutput代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    // 1.遍历结果
    NSMutableArray *resultArray = [NSMutableArray array];
    for (AVMetadataMachineReadableCodeObject *result in metadataObjects) {
        [resultArray addObject:result.stringValue];
    }
    
    // 2.将结果回调出去
    self.resultCallBack(resultArray);
}




@end
